﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using AutodeskInventorInterfaces.Model;
using AutodeskInventorInterfaces.Model.Exceptions;
using AutodeskInventorInterfaces.Service;
using Inventor;
using HttpGet = System.Web.Mvc.HttpGetAttribute;
using HttpPost = System.Web.Mvc.HttpPostAttribute;
using HttpDelete = System.Web.Mvc.HttpDeleteAttribute;
using AutodeskInventorInterfaces.Extend;
using System.IO;
using System.Threading;
using AutodeskInventorInterfaces.Model.Translators;
using ICSharpCode.SharpZipLib.Zip;

namespace AutodeskInventorInterfaces.Controllers
{
  public class HomeController : Controller
  {
    public ActionResult Index()
    {
      ViewBag.Title = "Autodesk Inventor Interfaces";
      return View();
    }

    private JsonResult JsonSuccess(object data)
    {
      return Json(new
      {
        code = 0,
        data
      }, JsonRequestBehavior.AllowGet);
    }

    /// <summary>
    /// 获取所有的零部件模板文件列表
    /// </summary>
    /// <returns></returns>
    public ActionResult GetPartFiles()
    {
      return JsonSuccess(InventorApplication.GetPartFiles().Map(item => item.ToRelativePath()));
    }

    /// <summary>
    /// 克隆指定路径的零部件模板
    /// </summary>
    /// <param name="partFile"></param>
    /// <returns></returns>
    [HttpPost]
    public JsonResult CloneFile([FromUri] string sourceFile)
    {
      var templatePath = sourceFile.ToAbsolutePath();
      if (!templatePath.IsAssemblyFile())
      {
        return JsonSuccess(InventorApplication.CloneFile(templatePath));
      }
      else
      {
        return JsonSuccess(InventorApplication.CloneAssemblyDocument(templatePath));
      }
    }

    /// <summary>
    /// 将指定的装配文件以及关联文件打包zip
    /// </summary>
    /// <param name="assFile"></param>
    /// <returns></returns>
    [HttpPost]
    public JsonResult PackageFiles([FromUri] string assemblyFile)
    {
      var assemblyFileInfo = new FileInfo(assemblyFile.ToAbsolutePath());
      assemblyFile = assemblyFileInfo.FullName;
      var refFiles = InventorApplication.GetAssemblyReferencedFiles(assemblyFile);
      var zipFileName = assemblyFileInfo.OnlyName();
      var zipFileFullName = $"{assemblyFileInfo.DirectoryName}\\{zipFileName}.zip";
      var zipFile = ZipFile.Create(zipFileFullName);

      zipFile.BeginUpdate();
      zipFile.Add(assemblyFile, $"{zipFileName}\\{assemblyFileInfo.Name}");
      foreach (var file in refFiles)
      {
        var fileInfo = new FileInfo(file);
        zipFile.Add(file.ToAbsolutePath(), $"{zipFileName}\\{fileInfo.Name}");
      }
      zipFile.CommitUpdate();
      zipFile.Close();
      return JsonSuccess(zipFileFullName);
    }

    /// <summary>
    /// 查询指定零部件的参数列表
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public JsonResult GetParameters([FromUri] string partFile)
    {
      var groups = InventorApplication.GetParameters(partFile.ToAbsolutePath(), p =>
      {
        return p.ToClientParameter();
      });
      var docParams = new List<ClientDocumentParameter>();
      foreach (var ety in groups)
      {
        docParams.Add(new ClientDocumentParameter {
          Template = ety.Key,
          Parameters = ety.Value as List<ClientParameter>
        });
      }
      return JsonSuccess(docParams);
    }

    /// <summary>
    /// 设置指定零部件文档的参数并生成DWG格式的文件，同时另存零部件文件为副本
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    public JsonResult SetParameters([FromBody] SetParametersParams setParams)
    {
      if (string.IsNullOrEmpty(setParams.Template) || !System.IO.File.Exists(setParams.Template.ToAbsolutePath()))
      {
        throw InventorException.模板零部件参数无效;
      }
      var templatePath = setParams.Template.ToAbsolutePath();
      dynamic partDoc = InventorApplication.OpenDocument(templatePath);
      InventorApplication.SetParameters(partDoc, setParams.Documents);
      return JsonSuccess(true);
    }

    /// <summary>
    /// 获取孔特征参数
    /// </summary>
    /// <param name="partFile"></param>
    /// <returns></returns>
    [HttpGet]
    public JsonResult GetHoleFeatures([FromUri] string partFile)
    {
      try
      {
        var features = InventorApplication.GetClientHoleFeatures(partFile.ToAbsolutePath());
        return JsonSuccess(features);
      }
      catch (Exception ex)
      {
        throw InventorException.未知错误.Create("获取孔特征参数失败！").SetDetail(ex.Message);
      }
    }

    /// <summary>
    /// 设置孔特征参数
    /// </summary>
    /// <param name="setParams"></param>
    /// <returns></returns>
    [HttpPost]
    public JsonResult SeHoleFeatures([FromBody] SetHoleFeatureParams setParams)
    {
      if (string.IsNullOrEmpty(setParams.Template) || !System.IO.File.Exists(setParams.Template.ToAbsolutePath()))
      {
        throw InventorException.模板零部件参数无效;
      }
      var templatePath = setParams.Template.ToAbsolutePath();

      try
      {
        InventorApplication.SetHoleFeatures(templatePath, setParams.HoleFeatures);
        return JsonSuccess(true);
      }
      catch (Exception ex)
      {
        throw InventorException.孔特征设置失败.Create().SetDetail(ex.Message);
      }
    }

    /// <summary>
    /// 获取支持的导出格式
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public JsonResult GetTranslators()
    {
      var addins = new ArrayList();
      foreach (var addIn in InventorApplication.Application.ApplicationAddIns)
      {
        var transAddIn = addIn as TranslatorAddIn;
        if (transAddIn != null && transAddIn.AddInType == ApplicationAddInTypeEnum.kTranslationApplicationAddIn)
        {
          try
          {
            addins.Add(new { Name = transAddIn.DisplayName, Id = transAddIn.ClassIdString });
          }
          catch (Exception e) { }

        }
      }
      return JsonSuccess(addins);
    }

    /// <summary>
    /// 导出文档
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    public JsonResult Export([FromBody] ExportParams exportParams)
    {
      var exports = exportParams.Exports;
      var file = exportParams.File.ToAbsolutePath();
      var doc = InventorApplication.OpenDocument(file);
      var fileInfo = new FileInfo(file);
      var fileName = $"{fileInfo.Directory}\\{fileInfo.OnlyName()}";
      object dwgFile = null;
      if (exports.DWG)
      {
        dwgFile = InventorTranslator.TranslatorDWG.Translate(doc, fileName, exports);
      }
      object sketchFile = null;
      if (exports.Sketch)
      {
        sketchFile = InventorTranslator.TranslatorSketch.Translate(doc, fileName, exports);
      }
      object stlFile = null;
      if (exports.STL)
      {
        stlFile = InventorTranslator.TranslatorSTL.Translate(doc, fileName, exports);
      }
      return JsonSuccess(new
      {
        dwgFile,
        sketchFile,
        stlFile,
      });
    }

    /// <summary>
    /// 关闭指定路径的文档
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    [HttpPost]
    public JsonResult CloseDocument([FromUri] string file)
    {
      InventorApplication.CloseDocument(file.ToAbsolutePath());
      return JsonSuccess(true);
    }

    /// <summary>
    /// 关闭所有已打开的文档
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    public JsonResult CloseAllDocuments()
    {
      InventorApplication.CloseAllDocuments();
      return JsonSuccess(true);
    }

    /// <summary>
    /// 上传零部件模板文件
    /// </summary>
    /// <param name="uploadFiles"></param>
    /// <returns></returns>
    [HttpPost]
    public JsonResult UploadTemplatePartFile([FromBody] UploadFileData[] uploadFiles = null)
    {
      var uploadedFiles = new ArrayList();
      if (Request.Files.Count > 0)
      {
        //标准的POST上传零部件模板文件
        foreach (HttpPostedFile postedFile in Request.Files)
        {
          var postedFileInfo = new FileInfo(postedFile.FileName);
          var saveFileName = $"{AppContext.BaseDirectory}Parts\\{postedFileInfo.Name}";
          postedFile.SaveAs(saveFileName);
          uploadedFiles.Add(saveFileName.ToRelativePath());
        }
      }
      else if (uploadFiles != null && uploadFiles.Length > 0)
      {
        //自定义的JSON格式上传零部件模板文件
        foreach (UploadFileData fileData in uploadFiles)
        {
          if (!string.IsNullOrEmpty(fileData.Data))
          {
            var buffer = Convert.FromBase64String(fileData.Data);
            var uploadFileName = $"{AppContext.BaseDirectory}Parts\\{fileData.FileName}";
            System.IO.File.WriteAllBytes(uploadFileName, buffer);
            uploadedFiles.Add(uploadFileName.ToRelativePath());
          }
        }
      }

      return JsonSuccess(uploadedFiles);
    }

    /// <summary>
    /// 删除指定的模板文件
    /// </summary>
    /// <param name=""></param>
    /// <returns></returns>
    [HttpPost]
    public JsonResult RemoveTemplatePartFile([FromUri] string partFile)
    {
      if (string.IsNullOrEmpty(partFile))
      {
        throw InventorException.参数错误;
      }
      InventorApplication.RemoveTemplatePartFile(partFile.ToAbsolutePath());
      return JsonSuccess(true);
    }
  }
}
